import { MessageNum } from 'API/crm/message'
import { QueryUnreadCount } from 'API/admin'
import { WaitingQueryOaExamineList } from 'API/oa/examine.js'

import { compareObj } from '@/utils/lib.js'

const state = {
	statusMap: {
		0: {status: 0, label: '待审核', color: '#ffc539', bg: 'rgba(255,197,57,0.1)', icon: 'wk-time'},
		1: {status: 1, label: '审核通过', color: '#20b559', bg: 'rgba(32,181,89,0.1)', icon: 'wk-check-fill'},
		2: {status: 2, label: '审核拒绝', color: '#f95a5a', bg: 'rgba(249,90,90,0.1)', icon: 'wk-close-fill'},
		3: {status: 3, label: '审核中', color: '#398dff', bg: 'rgba(57,141,255,0.1)', icon: 'wk-time'},
		4: {status: 4, label: '已撤回', color: '#999', bg: 'rgba(153,153,153,0.1)', icon: 'wk-reset'},
		5: {status: 5, label: '未提交', color: '#d9d9d9', bg: 'rgba(217,217,217,0.1)', icon: 'wk-time'},
		6: {status: 6, label: '创建', color: '#2362FB', bg: 'rgba(35,98,251,0.1)', icon: 'wk-plus'},
		7: {status: 7, label: '已删除', color: '#bfbfbf', bg: 'rgba(35,98,251,0.1)', icon: 'wk-invalid'},
		8: {status: 8, label: '已作废', color: '#bfbfbf', bg: 'rgba(191,191,191,0.1)', icon: 'wk-invalid'},
		10: {status: 10, label: '正常', color: '#20b559', bg: 'rgba(32,181,89,0.1)', icon: 'wk-check-fill'}
	},
	auditType: {
		1: '负责人主管',
		2: '{length}人或签',
		3: '{length}人会签',
		4: '上一级审批人主管'
	},

	backlogTotal: 0, // 待办事项总数
	backlogDetail: {}, // 待办事项数量明细
	backlogLoadingFlag: false // 待办事项加载标志
}

const getters = {
	calcStatus: state => status => state.statusMap[status] || {},
	calcAuditType: state => status => state.auditType[status],

	backlogTotal: state => state.backlogTotal,
	backlogDetail: state => state.backlogDetail,
}

let heartbeatTimer = null
let duration = 10 * 60 * 1000 // 待办事项心跳间隔

const actions = {
	startHeartbeat({dispatch, state}) {
		const token = uni.getStorageSync('token') || null
		if (!token) {
			dispatch('stopHeartbeat')
		} else {
			dispatch('getBacklogTotal')
		}
	},

	getBacklogTotal({ commit, dispatch, state }) {
		// 判断是否正在加载，节流
		if (state.backlogLoadingFlag) return;
		commit('SET_BACKLOG_LOADING_FLAG', true)

		// 清除上一个定时器
		if (heartbeatTimer) {
			clearTimeout(heartbeatTimer)
			heartbeatTimer = null
		}

		// 判断是否有token
		if (!uni.getStorageSync('token')) {
			commit('SET_BACKLOG_TOTAL', 0)
			commit('SET_BACKLOG_LOADING_FLAG')
			commit('SET_BACKLOG_DETAIL', {})
			return
		}

		Promise.all([
			MessageNum(),
			// QueryUnreadCount(),
			WaitingQueryOaExamineList({
				limit: 1,
				page: 1,
				status: 1
			})
		]).then(resArr => {
			const res = { ...resArr[0], ...resArr[1] }
			res.examineNum = resArr[2].totalRow
			dispatch('setBacklogNum', res)
			dispatch('nextHeartbeat')
		}).catch(() => {
			dispatch('nextHeartbeat')
		})
	},

	setBacklogNum({ commit, state }, data) {
		const backlogKeys = [
			'todayCustomer',
			'followLeads',
			'followCustomer',
			'putInPoolRemind',
			'endContract',
			'checkContract',
			'checkReceivables',
			'remindReceivablesPlan',
			'todayLeads',
			'todayBusiness',
			'examineNum'
		]
		const messageKeys = [
			'announceCount',
			'logCount',
			'examineCount',
			'taskCount',
			'crmCount',
			'eventCount'
			// 'knowledgeCount'
		]

		const res = {
			backlogDetail: {},
			backlogNum: 0,

			messageDetail: {},
			messageNum: 0
		}

		backlogKeys.forEach(key => {
			if (data.hasOwnProperty(key)) {
				res.backlogDetail[key] = Number(data[key]) || 0
				res.backlogNum += res.backlogDetail[key]
			} else {
				res.backlogDetail[key] = 0
			}
		})

		messageKeys.forEach(key => {
			if (data.hasOwnProperty(key)) {
				res.messageDetail[key] = Number(data[key]) || 0
				res.messageNum += res.messageDetail[key]
			} else {
				res.messageDetail[key] = 0
			}
		})

		commit('SET_BACKLOG_TOTAL', res.backlogNum + res.messageNum)
		commit('SET_BACKLOG_DETAIL', res)
	},

	nextHeartbeat({ commit, dispatch }) {
		commit('SET_BACKLOG_LOADING_FLAG')
		if (heartbeatTimer) {
			clearTimeout(heartbeatTimer)
		}
		heartbeatTimer = null
		heartbeatTimer = setTimeout(() => {
			dispatch('startHeartbeat')
		}, duration)
	},

	stopHeartbeat({ commit }) {
		if (heartbeatTimer) {
			clearTimeout(heartbeatTimer)
			heartbeatTimer = null
		}
		commit('SET_BACKLOG_TOTAL', 0)
		commit('SET_BACKLOG_LOADING_FLAG')
		commit('SET_BACKLOG_DETAIL', {})
	}
}

const mutations = {
	SET_BACKLOG_LOADING_FLAG(state, flag = false) {
		state.backlogLoadingFlag = flag
	},
	SET_BACKLOG_TOTAL(state, num) {
		state.backlogTotal = num
	},
	SET_BACKLOG_DETAIL(state, data = {}) {
		state.backlogDetail = data
	}
}

export default {
	namespaced: true,
	state,
	getters,
	actions,
	mutations
}
